package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 反转链表Ⅱ
 * https://leetcode.cn/problems/reverse-linked-list-ii/
 *
 * @time 2024/1/3
 */
public class ReverseBetween {

    public ListNode reverseBetween(ListNode head, int left, int right) {

        List<Integer> list = toList(head);
        reverseList(list, left - 1, right - 1);
        ListNode tmp = head;
        for (Integer val : list) {
            if (tmp.val != val) {
                tmp.val = val;
            }
            tmp = tmp.next;
        }
        return head;
    }

    private List<Integer> toList(ListNode head) {
        ListNode tmp = head;
        List<Integer> list = new ArrayList<>();
        while (tmp != null) {
            list.add(tmp.val);
            tmp = tmp.next;
        }
        return list;
    }

    private void reverseList(List<Integer> list, int left, int right) {
        for (int i = 0; i <= (right - left) / 2; i++) {
            int tmp = list.get(i + left);
            list.set(i + left, list.get(right - i));
            list.set(right - i, tmp);
        }
    }
}
